package com.google.appengine.twitter.interfaces.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.twitter.security.Authentication;
import com.google.appengine.twitter.security.AuthenticationBuilder;
import com.google.appengine.twitter.security.AuthenticationManager;
import com.google.appengine.twitter.security.AuthenticationResult;
import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class SigninServlet extends HttpServlet {

	private static final long serialVersionUID = 8216957673726935562L;
	
	@Inject
	private AuthenticationManager authenticationManager;

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		
		String usernameOrEmail = request.getParameter("session[username_or_email]");
		String password = request.getParameter("session[password]");
		boolean rememberMe = request.getParameter("remember_me") != null;
		String authenticityToken = request.getParameter("authenticity_token");
		
		Authentication authentication = AuthenticationBuilder.usernameOrEmail(usernameOrEmail)
															 .password(password)
															 .rememberMe(rememberMe)
															 .authenticityToken(authenticityToken)
															 .build();
		
		AuthenticationResult result = authenticationManager.authenticate(authentication);
		
		if (result.successful()) {
			response.sendRedirect("/home");
		} else {
			getServletContext().getRequestDispatcher("/login.html").forward(request, response);
		}
		
	}
	
	
	
}
